<template>
  <div class="app-container">
    <!-- 条件栏 -->
    <NewPageFilter
      v-model:query="filterInfo.query"
      :filter-list="filterInfo.list"
      :filter-btn="filterInfo.searchBtn"
      :clear-type="clearType"
    >
      <template v-slot:filter-winBiddingProductId>
        <el-input
          v-model="filterInfo.query.winBiddingProductName"
          class="not-mongolia"
          type="input"
          :disabled="true"
          placeholder="请选择中标产品"
        >
          <template #append>
            <el-icon @click="checkProduct(1)"><MoreFilled /></el-icon>
          </template>
        </el-input>
      </template>
      <template v-slot:filter-nonBiddingProductId>
        <el-input
          v-model="filterInfo.query.nonBiddingProductName"
          class="not-mongolia"
          type="input"
          :disabled="true"
          :placeholder="'请选择非中标产品'"
        >
          <template #append>
            <el-icon @click="checkProduct(2)"><MoreFilled /></el-icon>
          </template>
        </el-input>
      </template>
    </NewPageFilter>
    <NewPageFilter :filter-btn="filterInfo.btnList">
      <template v-slot:filter-uploadFile>
        <el-upload
          :headers="uploadInfo.headers"
          :show-file-list="false"
          :on-error="uploadError"
          :on-success="uploadSuccess"
          :before-upload="beforeUpload"
          :action="uploadInfo.action"
        >
          <el-button>excel导入</el-button>
        </el-upload>
      </template>
    </NewPageFilter>
    <!-- 表格 -->
    <table-container
      :refresh="tableInfo.refresh"
      :init-curpage="tableInfo.initCurpage"
      v-model:data="tableInfo.data"
      :api="tableInfo.api"
      :tab-index="true"
      :check-box="false"
      :query="filterInfo.query"
      :field-list="tableInfo.fieldList"
      :handle="tableInfo.handle"
    ></table-container>
    <!-- 新增修改弹窗 -->
    <page-dialog
      v-if="dialogInfo.visible"
      :title="dialogInfo.title[dialogInfo.type]"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <!-- form -->
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="formInfo.ref"
        :data="formInfo.data"
        :field-list="formInfo.fieldList"
        :rules="formInfo.rules"
        :label-width="formInfo.labelWidth"
      >
        <template v-slot:form-winBiddingProductId>
          <el-input
            v-model="formInfo.data.winBiddingProductName"
            class="not-mongolia"
            type="input"
            :disabled="true"
            placeholder="请选择中标产品"
          >
            <template #append>
              <el-icon @click="checkProduct(3)"><MoreFilled /></el-icon>
            </template>
          </el-input>
        </template>
        <template v-slot:form-nonBiddingProductId>
          <el-input
            v-model="formInfo.data.nonBiddingProductName"
            class="not-mongolia"
            type="input"
            :disabled="true"
            :placeholder="'请选择非中标产品'"
          >
            <template #append>
              <el-icon @click="checkProduct(4)"><MoreFilled /></el-icon>
            </template>
          </el-input>
        </template>
             <!-- 转换比 -->
        <template v-slot:form-conversionRatio>

            <el-input-number
              v-model.lazy="formInfo.data.conversionRatio"
              clearable
              controls-position="right"
              :precision="2"
              :min="0"
              :max="99999"
            />
        </template>
      </page-form>
      <table-container
        :data="[formInfo.data]"
        :pager="false"
        :check-box="false"
        :isDynamic="false"
        :field-list="tableInfo.fieldList"
      ></table-container>
    </page-dialog>
    <!-- 添加项目 -->
    <SelectProject
      v-if="selectProjectObj.visible"
      v-model:show-dialog="selectProjectObj.visible"
      :query="selectProjectObj.query"
      :api="selectProjectObj.api"
      :check-box="false"
      :highlightRow="true"
      @callback="selectProduct"
    />
  </div>
</template>

<script setup name="bidWinning">
import {
  winNonBiddingMappingPage,
  postWinNonBiddingMapping,
  putWinNonBiddingMapping,
  winOrNonBiddingPage,
  notMappingProduct,
} from '@/api/core.js'
const SelectProject = defineAsyncComponent(() => import('./selectProject'))
import { ElLoading, ElMessage } from 'element-plus'
import axios from 'axios'
import { exportTemplateExcel } from '@/api/pub.js'

const { proxy } = getCurrentInstance()
const uploadInfo = ref({
  action: axios.defaults.baseURL + '/core/products/winNonBiddingMapping/import',
  headers: {
    Authorization: proxy.$store.state.user.token,
  },
  loading: {},
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    sort: 'create_time desc',
  },
  copyQueryMap: {},
  list: [
    {
      label: '中标产品',
      value: 'winBiddingProductId',
      event: search,
      slot: true,
    },
    {
      label: '非中标产品',
      value: 'nonBiddingProductId',
      event: search,
      slot: true,
    },
  ],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      show: proxy.$permission('bidWinning:add'),
      event: create,
    },
    {
      type: 'button',
      label: '下载模板',
      event: downloadTemplate,
      show: proxy.$permission('bidWinning:download'),
    },
    {
      type: 'slot',
      value: 'uploadFile',
      show: proxy.$permission('bidWinning:importExcel'),
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  fieldList: [
    { label: '中标产品名称', value: 'winBiddingProductName' },
    { label: '中标产品编码', value: 'winBiddingProductCode' },
    { label: '中标产品规格', value: 'winBiddingProductStandard' },
    { label: '非中标产品名称', value: 'nonBiddingProductName' },
    { label: '非中标产品编码', value: 'nonBiddingProductCode' },
    { label: '非中标产品规格', value: 'nonBiddingProductStandard' },
    { label: '转换比', value: 'conversionRatio' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('bidWinning:update'),
      },
    ],
  },
})
// 表单相关
const formInfo = ref({
  ref: null,
  data: {
    conversionRatio: 1
  },
  fieldList: [
    {
      label: '中标产品',
      value: 'winBiddingProductId',
      type: 'slot',
      required: true,
    },
    {
      label: '非中标产品',
      value: 'nonBiddingProductId',
      type: 'slot',
      required: true,
    },
    {
      label: '转换比',
      value: 'conversionRatio',
      type: 'slot',
      required: true,
    },
  ],
  rules: {
    winBiddingProductId: [
      { required: true, message: '请选择中标产品', trigger: 'change' },
    ],
    nonBiddingProductId: [
      { required: true, message: '请选择非中标产品', trigger: 'change' },
    ],
    conversionRatio: [
      { required: true, message: '请输入转换比', trigger: 'blur' },
    ],
  },
  labelWidth: '100px',
})
// 弹窗相关
const dialogInfo = ref({
  title: {
    create: '添加',
    update: '修改',
  },
  visible: false,
  type: '',
  width: '1200',
  btLoading: false,
  btList: [
    { label: '关闭', type: '', icon: '', event: close, show: true },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      event: save,
      saveLoading: false,
      show: true,
    },
  ],
})
const clearType = ref(true)
const selectProjectObj = ref({
  visible: false,
  api: winOrNonBiddingPage,
  query: {
    idNotIn: '',
    isWinning: null,
  },
})
// 当前打开的产品弹窗
const currentProdNum = ref(0)

onMounted(() => {
  filterInfo.value.copyQueryMap = proxy.$fn.deepClone(filterInfo.value.query)
  getList()
})

// 获取列表
function getList() {
  tableInfo.value.api = winNonBiddingMappingPage
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
function clearSearch() {
  clearType.value = !clearType.value
  filterInfo.value.query = proxy.$fn.deepClone(filterInfo.value.copyQueryMap)
  search()
}
function downloadTemplate() {
  exportTemplateExcel('mapping_win_non_bidding_product_import_template').then(
    (res) => {
      if (res) {
        proxy.$fn.parseExcel(res)
      }
    }
  )
}
// 创建
function create() {
  formInfo.value.data = {
    conversionRatio: 1
  }
  dialogInfo.value.type = 'create'
  dialogInfo.value.visible = true
}
// 编辑
function update(data) {
  dialogInfo.value.type = 'update'
  dialogInfo.value.visible = true
  // 显示信息
  formInfo.value.data = { ...data }
}
function close() {
  dialogInfo.value.visible = false
  formInfo.value.data = {}
}
function checkProduct(val) {
  if (val === 1) {
    selectProjectObj.value.query.idNotIn =
      filterInfo.value.query.winBiddingProductId || ''
    selectProjectObj.value.query.isWinning = '1'
    selectProjectObj.value.api = winOrNonBiddingPage
  } else if (val === 2) {
    selectProjectObj.value.query.idNotIn =
      filterInfo.value.query.nonBiddingProductId || ''
    selectProjectObj.value.query.isWinning = '0'
    selectProjectObj.value.api = winOrNonBiddingPage
  } else if (val === 3) {
    selectProjectObj.value.query.idNotIn =
      formInfo.value.data.winBiddingProductId || ''
    selectProjectObj.value.query.isWinning = '1'
    selectProjectObj.value.api = notMappingProduct
  } else if (val === 4) {
    selectProjectObj.value.query.idNotIn =
      formInfo.value.data.nonBiddingProductId || ''
    selectProjectObj.value.query.isWinning = '0'
    selectProjectObj.value.api = notMappingProduct
  }
  currentProdNum.value = val
  selectProjectObj.value.visible = true
}
function selectProduct(row) {
  if (currentProdNum.value === 1) {
    filterInfo.value.query.winBiddingProductId = row.id || ''
    filterInfo.value.query.winBiddingProductName = row.commonName || ''
  } else if (currentProdNum.value === 2) {
    filterInfo.value.query.nonBiddingProductId = row.id || ''
    filterInfo.value.query.nonBiddingProductName = row.commonName || ''
  } else if (currentProdNum.value === 3) {
    formInfo.value.data.winBiddingProductId = row.id || ''
    formInfo.value.data.winBiddingProductName = row.commonName || ''
    formInfo.value.data.winBiddingProductCode = row.code || ''
    formInfo.value.data.winBiddingProductStandard = row.standard || ''
    formInfo.value.data.conversionRatio = formInfo.value.data.conversionRatio
  } else if (currentProdNum.value === 4) {
    formInfo.value.data.nonBiddingProductId = row.id || ''
    formInfo.value.data.nonBiddingProductName = row.commonName || ''
    formInfo.value.data.nonBiddingProductCode = row.code || ''
    formInfo.value.data.nonBiddingProductStandard = row.standard || ''
    formInfo.value.data.conversionRatio = formInfo.value.data.conversionRatio
  }
}
function save() {
  formInfo.value.ref.validate((valid) => {
    if (valid) {
      let api
      const params = formInfo.value.data
      const type = dialogInfo.value.type
      if (type === 'create') {
        api = postWinNonBiddingMapping
      } else if (type === 'update') {
        api = putWinNonBiddingMapping
      } else {
        return
      }
      proxy
        .$handleAPI(type, api, params)
        .then((res) => {
          if (res.success) {
            dialogInfo.value.visible = false
            tableInfo.value.refresh = Math.random()
          }
        })
        .catch((e) => {})
    }
  })
}
function beforeUpload(file) {
  //发生请求时打开加载动画
  uploadInfo.value.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  let fileType = ['xlsx']
  let fileSize = proxy.$store.state.permission.systemConfig.max_file_size
  let isFileType = fileType.some((type) => {
    console.log(file.name.split('.')[file.name.split('.').length - 1] === type)
    return file.name.split('.')[file.name.split('.').length - 1] === type
  })
  const isLt = file.size / 1024 / 1024 < fileSize
  if (!isFileType) {
    proxy.$message.error({
      message: `文件格式不正确, 请上传 ${fileType.join(' / ')} 格式文件!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  if (!isLt) {
    proxy.$message.error({
      message: `上传文件大小不能超过 ${fileSize} MB!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  return isFileType && isLt
}
function uploadSuccess(resp) {
  console.log(resp)
  uploadInfo.value.loading.close()
  if (resp && resp.success) {
    ElMessage.success({
      duration: 3000,
      showClose: true,
      message: resp.msg,
    })
    getList()
  } else {
    ElMessage.error({
      message: resp.msg,
      duration: 3000,
      showClose: true,
    })
  }
}
function uploadError(err) {
  if (err) {
    ElMessage.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  uploadInfo.value.loading.close()
}
</script>

<style scoped></style>
